package com.weilive.pay.gate;

import java.net.URLDecoder;
import java.util.Map;

import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.weilive.core.netty.http.HttpServlet;
import com.weilive.core.utils.HttpUtils;
import com.weilive.pay.service.ali.AlipayService;

@Service
public class AlipayServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(AlipayQueryServlet.class);
	@Autowired
	private AlipayService alipayService;

	@Override
	public String getServletPath() {
		return "/pay/alipay";
	}

	@Override
	public HttpResponse processRequest(HttpRequest request) throws Exception {
		// post
		String temStr = URLDecoder.decode(request.getContent().toString(CharsetUtil.UTF_8), "UTF-8");
		// 处理支付结果
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = HttpUtils.getParamsMap(temStr);

		if (params.isEmpty()) {
			return createJsonResponse("fail");
		}
		try {
			String check = alipayService.checkAndSaveLog(params);

			// 如果ok,就直接返回
			if (check.equals("ok")) {
				logger.info("收到支付宝支付通知, params=" + params.toString() + ",返回结果=success");
				return createJsonResponse("success");
			}
			String result = alipayService.pay(params);
			logger.info("收到支付宝支付通知, params=" + params.toString() + ",返回结果=" + result);
			return createJsonResponse(result);

		} catch (Exception e) {
			e.printStackTrace();
			logger.info("收到支付宝支付通知, params=" + params.toString() + ",返回结果=fail");
			return createJsonResponse("fail");
		}
	}
}